<template>
  <el-dialog :destroy-on-close="true" title="新增员工" :visible="showDialog" @close="cancelAddition">
    <el-form ref="form" label-width="120px" :data="employeeInfo" :rules="rules" :model="employeeInfo ">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="employeeInfo.username" style="width:80%" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="employeeInfo.mobile" style="width:80%" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="入职日期" prop="timeOfEntry">
        <el-date-picker v-model="employeeInfo.timeOfEntry" style="width:80%" placeholder="请选择入职时间" @change="validateTwoTimeDatas" />
      </el-form-item>
      <el-form-item label="聘用形式" prop="formOfEmployment">
        <el-select v-model="employeeInfo.formOfEmployment" style="width:80%" placeholder="请选择" @blur="validateHireType">
          <el-option
            v-for="item in employmentEnum.hireType"
            :key="item.id"
            :label="item.value"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工号" prop="workNumber">
        <el-input v-model="employeeInfo.workNumber" style="width:80%" placeholder="请输入工号" />
      </el-form-item>
      <el-form-item label="部门" prop="departmentName">
        <el-input v-model="employeeInfo.departmentName" style="width:80%" placeholder="请选择部门" @focus="getDepartments" />
        <div v-if="treeData.length > 0" class="treeWrapper">
          <el-tree class="treeDeparment" :default-expand-all="true" :data="treeData" :props="{label:'name'}" @node-click="selectNode" />
        </div>
      </el-form-item>
      <el-form-item label="转正日期" prop="correctionTime">
        <el-date-picker v-model="employeeInfo.correctionTime" style="width:80%" placeholder="请选择转正时间" @change="validateTwoTimeDatas" />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-row type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="cancelAddition">取消</el-button>
          <el-button type="primary" size="small" @click="addEmployee">确定</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>
<script>
import employmentEnum from '@/api/constant/employees'
import { getDepartments } from '@/api/departments'
import { convertTreeData } from '@/utils'
import { addEmployee } from '@/api/employees'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const checkTime = (rule, value, callback) => {
      if (!this.employeeInfo.timeOfEntry || !this.employeeInfo.correctionTime) {
        // 两个时间有一个不填都不校验
        callback()
      } else {
        const timeOfEntry = this.employeeInfo.timeOfEntry.getTime()
        const correctionTime = this.employeeInfo.correctionTime.getTime()
        timeOfEntry < correctionTime ? callback() : callback(new Error('入职前不能转正'))
      }
    }

    return {
      employmentEnum,
      employeeInfo: {
        username: '',
        mobile: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        timeOfEntry: '',
        correctionTime: ''
      },
      rules: {
        username: [
          { required: true, message: '用户姓名不能为空', trigger: 'blur' },
          { min: 1, max: 4, message: '用户姓名为1-4位' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        formOfEmployment: [{ required: true, message: '聘用形式不能为空', trigger: 'change' }],
        workNumber: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
        departmentName: [
          { required: true, message: '部门不能为空', trigger: 'change' },
          { required: true, message: '部门不能为空', trigger: 'blur' }
        ],
        timeOfEntry: [
          { required: true, message: '入职时间不能为空', trigger: 'blur' },
          { trigger: 'blur', validator: checkTime },
          { trigger: 'change', validator: checkTime }
        ],
        correctionTime: [
          { trigger: 'change', validator: checkTime }
        ]
      },
      treeData: []
    }
  },
  methods: {
    validateHireType() {
      // element ui的表单校验 <el-select></el-select>在校验规则中绑定trigger:'blur'无法触发校验,直接监听该项的blur事件进行校验
      this.$refs.form.validateField('formOfEmployment')
    },
    async getDepartments() {
      const { depts } = await getDepartments()
      this.treeData = convertTreeData(depts, '')
      this.showTreeData = true
    },
    selectNode(data) {
      this.employeeInfo.departmentName = data.name
      this.treeData = []
    },
    async addEmployee() {
      try {
        const isValid = await this.$refs.form.validate()
        if (isValid) {
          await addEmployee(this.employeeInfo)
          this.$message.success('新增员工成功!')
          this.$refs.form.resetFields()
          this.$emit('update:showDialog', false)
          this.$emit('addEmployee')
        }
      } catch (error) {
        console.dir(error)
      }
    },
    validateTwoTimeDatas() {
      this.$refs.form.validateField(['timeOfEntry', 'correctionTime'])
    },
    cancelAddition() {
      this.$refs.form.clearValidate()
      this.employeeInfo = {
        departmentName: ''
      }
      this.treeData = []
      this.$emit('update:showDialog', false)
    }
  }
}
</script>

<style lang="scss" scoped>
.treeWrapper {
  width: 300px;
  height: 300px;
  border: 1px solid #888;
  overflow: hidden;
  position: absolute;
  left: 0;
  z-index: 999;
  .treeDeparment {
    width: 317px;
    height: 100%;
    overflow-y: scroll;
  }
}
</style>
